<template>
    <div>
        <Drawer
                title="和卖家沟通"
                v-model="windowShow"
                width="480"
                :mask-closable="true"
        >
            <Layout>
                <Content class="">
                    <Scroll height="480">
                        <Card v-for="item in MessageList" :key="item.messageItemId" :value="item.messageItemId">
                            <Row>
                                <Col>
                                    <Avatar v-if="item.messageSenderId===userId" v-bind:src="userAvatar"
                                            size="15"></Avatar>
                                    <Avatar v-else v-bind:src="sellerAvatar" size="15"></Avatar>
                                </Col>
                                <Col>
                                    <p v-if="item.messageReceiverId===userId">{{item.senderName}}</p>
                                    <p v-else>{{userName}}</p>
                                </Col>
                                <Col>
                                    <p>{{item.messageSenderDate}}</p>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    {{ item.messageContent }}
                                </Col>
                            </Row>
                        </Card>
                    </Scroll>
                </Content>
                <Footer>
                    <Form class="footer">
                        <Button class="send" @click="sentToSeller">发送</Button>
                        <Input v-model="questionContent" type="textarea" :rows="4" placeholder="请输入您想咨询的问题"></Input>
                    </Form>
                </Footer>
            </Layout>
        </Drawer>
        <Row :gutter="16" style="height: fit-content">
            <Col span="16">
                <Card style="height:fit-content  ">
                    <Row slot="title" type="flex" justify="space-between" align="middle">
                        <Col>
                            <p style="font-weight: bolder;font-size: larger">{{ product.productName }}</p>
                        </Col>
                        <Col>
                            <p style="color: orangered;font-weight: bolder;font-size: larger">￥:{{product.price}}</p>
                        </Col>
                        <Col>
                            <p>剩余{{product.productStock}}件</p>
                        </Col>
                    </Row>
                    <p style="font-weight: bold">{{ product.productLocation }}</p>
                    <p>{{ product.productBrief }}</p>
                    <Row style="height: fit-content" :gutter="24">
                        <Col span="12">
                            <img v-bind:src="productCover" style="height: auto;width: 100%">
                        </Col>
                        <Col span="12">
                            <img v-bind:src="productPicture" style="height: auto;width: 100%">
                        </Col>
                    </Row>
                </Card>
                <Row :gutter="36" style="margin-top: 5px">
                    <Col>
                        <Button v-if="isStared" icon="md-heart" @click="stars(0)">取消点赞</Button>
                        <Button v-else icon="md-heart-outline" @click="stars(1)">点赞</Button>
                    </Col>
                    <Col>
                        <Button icon="md-cart" @click="addToCart">加入购物车</Button>
                    </Col>
                    <Col>
                        <Button icon="ios-text" @click="talkerToSeller">联系卖家</Button>
                    </Col>
                </Row>
            </Col>
            <Col span="6">
                <Card>
                    <div slot="title">
                        <Row>
                            <Col>
                                <Avatar v-bind:src="sellerAvatar"></Avatar>
                            </Col>
                            <Col>
                                <p style="font-weight: bolder;font-size: large">{{ seller.nickName }}</p>
                            </Col>
                        </Row>
                    </div>
                    <p>{{ seller.location }}</p>
                    <div>
                        <p slot="title">{{seller.signUpDate.slice(0,10)}}来到海淘~</p>
                        <p>已经卖出{{seller.soldNum}}件商品了</p>
                    </div>
                    <Row type="flex" align="middle">物流服务 :
                        <Rate disabled allow-half v-model="seller.logisticsLevel"/>
                        {{seller.logisticsLevel}}
                    </Row>
                    <Row type="flex" align="middle">商品质量 :
                        <Rate disabled allow-half v-model="seller.productLevel"/>
                        {{seller.productLevel}}
                    </Row>
                    <Row type="flex" align="middle">卖家服务 :
                        <Rate disabled allow-half v-model="seller.serviceLevel"/>
                        {{seller.serviceLevel}}
                    </Row>
                </Card>
            </Col>
        </Row>
        <!--界面展示-->
        <label>评论</label>
        <Row>
            <Col>
                <Input type="textarea" class="inputLen" v-model="comment.content" :rows="4"
                       placeholder="在法律允许的范围内畅所欲言">
                </Input>
            </Col>
            <Col>
                <Button type="primary" @click="addComment">发表评论</Button>
            </Col>
        </Row>
        <Col span="15">
            <Card v-for="(item,index) in commentList" :key="item.commentId" :value="commentId" padding="12">
                <br>
                <Row>
                    <Col>
                        <Row>
                            <avatar v-if="item.commentUserId===userId" v-bind:src="userAvatar" size="55"></avatar>
                            <avatar v-else v-bind:src="avatarList[index]" size="55"></avatar>
                        </Row>
                        <Row>
                            <Col>{{ item.commentUserName }}</Col>
                        </Row>
                    </Col>
                    <Col span="21">
                        <Card>
                            {{ item.content }}
                        </Card>
                        <Col>
                            {{ item.commentTime }}
                        </Col>
                    </Col>
                </Row>
            </Card>
        </Col>
    </div>
</template>

<script>
    import axios from "axios";
    import globalData from "@/utils/globalData";

    export default {
        name: "ProductBrief",
        data() {
            return {
                userId: globalData.USER.userId,
                userName: globalData.USER.nickName,
                sellerAvatar: '',
                productCover: '',
                productPicture: '',
                MessageList: [],
                windowShow: false,
                questionContent: "",
                productId: this.$route.params.productId,
                product: {},
                seller: {},
                isStared: false,
                commentList: [],
                avatarList: [],
                userAvatar: globalData.userAvatar,
                comment: {
                    commentProductId: 0,
                    commentUserId: "",
                    commentUserName: "",
                    content: '',
                    commentUUID: ''
                }
            }
        },
        created: function () {
            console.log(this.productId + "test")
            this.comment.commentProductId = this.productId
            this.comment.commentUserName = globalData.USER.nickName
            this.comment.commentUserId = globalData.USER.userId
            this.comment.commentUserUUID = globalData.USER.avatarUUId
            let self = this
            //获取产品信息
            axios({
                method: 'get',
                url: '/product/' + this.productId
            }).then(function (res) {
                self.product = res.data
                console.log(self.product)
                let my = self
                //获取商品封面
                axios({
                    method: 'get',
                    url: '/file/sig/product/' + self.product.coverUUID,
                    responseType: 'blob'
                }).then(function (res) {
                    my.productCover = window.URL.createObjectURL(res.data)
                })
                //获取商品照片
                axios({
                    method: 'get',
                    url: '/file/sig/product/' + self.product.pictureUUID,
                    responseType: 'blob'
                }).then(function (res) {
                    my.productPicture = window.URL.createObjectURL(res.data)
                })
                //获取卖家信息
                axios({
                    method: 'get',
                    url: '/user/' + self.product.belongToId
                }).then(function (res) {
                    my.seller = res.data
                })
                //获取卖家头像
                axios({
                    method: 'get',
                    url: '/file/sig/avatar/' + self.product.sellerUUID,
                    responseType: 'blob'
                }).then(function (res) {
                    my.sellerAvatar = window.URL.createObjectURL(res.data)
                })
            })
            //获取评论信息
            axios({
                method: 'get',
                url: 'comment/list/' + this.productId
            }).then(function (res) {
                self.commentList = res.data
                console.log("comment" + res.data)
                //获取每一个评论的头像
                let my = self
                self.avatarList = []
                for (let i = 0; i < self.commentList.length; i++) {
                    axios({
                        method: 'get',
                        url: '/file/sig/avatar/' + self.commentList[i].commentUserUUID,
                        responseType: 'blob'
                    }).then(function (res) {
                        my.$set(my.avatarList, i, window.URL.createObjectURL(res.data))
                    })
                }
            })
            //获取是否被点赞
            axios({
                method: 'get',
                url: 'product/stars/isS/' + globalData.USER.userId + "/" + this.productId
            }).then(function (res) {
                if (res.data)
                    self.isStared = true
            })
        },
        mounted() {
            let self = this
            if (this.windowShow) {
                this.timer = setInterval(() => {
                    self.getUnreadMessage()
                }, 1000)
            }
            //需要调用函数来让组件销毁的时候一并销毁掉setInterval，否则将会在切换到其他界面的时候仍然持续发起请求
            this.$once('hook:beforeDestroy', function () {
                clearTimeout(this.timer)
            })
        },
        methods: {
            getUnreadMessage() {
                let self = this
                axios({
                    method: 'get',
                    url: 'message/unread/' + globalData.USER.userId + "/" + this.seller.userId
                }).then(function (res) {
                    let newMessageList = res.data
                    for (let i = 0; i < newMessageList.length; i++) {
                        self.MessageList.push(newMessageList[i])
                    }
                })
            },
            addComment() {
                if (this.comment.content === '') {
                    this.$Notice.warning({
                        title: '您还没有输入内容',
                    });
                    return;
                }
                let self = this
                axios({
                    method: 'post',
                    url: '/comment',
                    data: this.comment
                }).then(function () {
                    self.$Notice.success({
                        title: '评论成功',
                        desc: '您的评论正在审核中~'
                    });
                    self.comment.content = ""
                })
            },
            addToCart() {
                let self = this
                axios({
                    method: 'post',
                    url: '/cart',
                    data: {
                        userId: globalData.USER.userId,
                        productId: this.productId,
                        productName: this.product.productName,
                        price: this.product.price,
                        sellerId: this.product.belongToId,
                        sellerName: this.product.belongToName,
                        coverUUID: this.product.coverUUID,
                        sellerUUID: this.product.sellerUUID
                    }
                }).then(function (res) {
                    console.log(res.data)
                    if (res.data) {
                        self.$Notice.success({
                            title: '添加到购物车成功',
                        });
                    } else {
                        self.$Notice.error({
                            title: '您已经添加过此商品',
                        });
                    }
                })
            },
            stars(act) {
                let self = this
                //后端
                axios({
                    method: 'patch',
                    url: 'product/stars/' + act + '/' + this.productId + "/"
                        + globalData.USER.userId + "/" + this.product.productName + "/" + this.product.coverUUID
                }).then(function (res) {
                    if (act === 1) {
                        if (res.data) {//如果成功点赞
                            self.$Notice.success({
                                title: "点赞成功！",
                            })
                            self.isStared = true;
                        }
                    } else {
                        self.product.starsNum -= 1
                        self.isStared = false;
                    }
                })
            },
            talkerToSeller() {
                //如果ID相同则不打开，上线后取消下面注释
                if (globalData.USER.userId === this.seller.userId) {
                    this.$Notice.warning({
                        title: "自问自答就没必要了吧"
                    })
                    return
                }

                let self = this
                //在这里试图获取全部聊天
                //如果List为null的话就新建talker
                axios({
                    method: 'get',
                    url: 'message/list/' + globalData.USER.userId + "/" + this.seller.userId
                }).then(function (res) {
                    // console.log("hello" + res.data.length+"LENGTH")
                    // if (res!==null) {
                    //     self.MessageList = res.data
                    // } else {
                    console.log(res+"RREESS")
                    axios({
                        method: 'post',
                        url: "/message/talker",
                        data: {
                            userId: globalData.USER.userId,
                            userName: globalData.USER.nickName,
                            userAvatarUUID:globalData.USER.avatarUUId,
                            otherId: self.seller.userId,
                            otherName: self.seller.nickName,
                            otherAvatarUUID: self.seller.avatarUUId,
                        }
                    }).then(function () {
                        console.log("??")
                    })
                    self.MessageList = res.data
                    // }
                })
                this.windowShow = true
            },
            sentToSeller() {
                axios({
                    method: 'post',
                    url: "/message/",
                    data: {
                        messageContent: this.questionContent,
                        messageSenderId: globalData.USER.userId,
                        senderName: globalData.USER.nickName,
                        messageReceiverId: this.seller.userId,
                        receiverName: this.seller.nickName
                    }
                })
                //没太看懂当时的做法
                this.MessageList.push({
                    messageSenderId: globalData.USER.userId,
                    messageItemId: new Date().getSeconds(),
                    messageContent: this.questionContent
                })
                //发送完之后清空发送框
                this.questionContent = ""
            }
        }
    }
</script>

<style>
    .send {
        position: relative;
        left: 80%;
        bottom: 5px;
    }

    .inputLen {
        width: 600px;
    }

    .footer {
        width: 420px;
        height: 120px;
        position: fixed;
        bottom: 15px;
        right: 15px;
    }
</style>